package com.gitee.slowcreator.http.executor.okhttp;

import com.gitee.slowcreator.http.config.HttpContextManager;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author zxw
 * @date 2023/3/18 下午10:24
 */
public class OkhttpTimeoutInterceptor implements Interceptor {

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {

        Request request = chain.request();
        // 默认没有超时时间
        int timeout = Optional.ofNullable(HttpContextManager.get().getRequestTimeout()).orElse(0);
        // 项目默认超时时间为-1 但是okhttp为0才是无限制超时时间 所以这边调整一下
        timeout = Math.max(timeout, 0);
        return chain.withConnectTimeout(5000, TimeUnit.MILLISECONDS)
                .withReadTimeout(timeout, TimeUnit.MILLISECONDS)
                .withWriteTimeout(timeout, TimeUnit.MILLISECONDS)
                .proceed(request);
    }
}
